# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

# _GATEWAY = 'http://pay.095pay.com/api/order/pay'
_GATEWAY = 'http://pay.095pay.com/zfapi/order/pay'
_QUERY_GATEWAY = 'http://query.095pay.com/zfapi/order/singlequery'

APP_CONF = {
    '29309': {
        'API_KEY': 'd7fa980ecfa99feef83f40c2a2c77204',
    },
    '30713': {  # dwcqqwap1.8%0---5000.京东wap1.5%0---1000
        'API_KEY': '0db678c510771ea673c9e25209208924',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


# 金阳支付接的是电玩城。
# 支付方式有：
# qq钱包，qqwap单笔限额都是（10----500），
# 微信wap的单笔限额是（10---5000），
# 京东钱包的单笔限额是（10---2000），
# 快捷的单笔限额是（10---4999）可以对接。

# ALIPAYWAP	手机支付宝WAP
# TENPAY	财付通
# WEIXIN	微信
# WEIXINWAP	手机微信WAP
# QQPAY	QQ钱包
# QQPAYWAP	手机QQ钱包WAP
# JDPAY	京东支付
# JDPAYWAP	手机京东支付
# BAIDUPAY	百度钱包支付
# UNIONPAY	银联扫码
# UNIONWAPPAY
def _get_pay_type(service):
    if service == 'alipay':
        return 'ALIPAYWAP'
    elif service == 'wxpay':
        return 'WEIXINWAP'
    elif service == 'qq':
        return 'QQPAYWAP'
    elif service == 'jd':
        return 'JDPAYWAP'
    elif service == 'quick':
        return 'UNIONWAPPAY'
    else:
        return 'FASTPAY'


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in parameter.keys():
        if parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s = s[0:len(s) - 1]
    s += key
    _LOGGER.info("jinyangpay sign str : %s", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_notify_sign(d, key):
    '''  生成下单签名 '''
    s = 'partner={}&ordernumber={}&orderstatus={}&paymoney={}{}'.format(
        d['partner'], d['ordernumber'], d['orderstatus'], d['paymoney'], key
    )
    _LOGGER.info("jinyangpay notify sign str : %s", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("jinyangpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + _GATEWAY + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('p1_mchtid', app_id),
        ('p2_paytype', _get_pay_type(service)),
        ('p3_paymoney', '%.2f' % pay_amount),
        ('p4_orderno', str(pay.id)),
        ('p5_callbackurl', '{}/pay/api/{}/jinyangpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('p6_notifyurl', '{}/pay/api/{}/jinyangpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, app_id)),
        ('p7_version', 'v2.8'),
        ('p8_signtype', '1'),  # int	1.MD5	签名加密方式
        ('p9_attach', 'charge'),
        ('p10_appname', ''),
        ('p11_isshow', '0'),  # 是否显示PC收银台
        ('p12_orderip', _get_device_ip(info)),
    ))
    if parameter_dict['p2_paytype'] == 'FASTPAY':
        parameter_dict['p13_memberid'] = '00000' + str(pay.user_id)
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("jinyangpay create  data: %s", parameter_dict)
    html_text = _build_form(parameter_dict)
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# ok
def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("jinyangpay notify data1: %s", data)
    _LOGGER.info("jinyangpay notify body: %s", request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['ordernumber']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('jinyangpay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['orderstatus'])
    trade_no = data['sysnumber']
    total_fee = float(data['paymoney'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 1:支付成功，非1为支付失败
    if trade_status == '1':
        _LOGGER.info('jinyangpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('p1_mchtid', app_id),
        ('p2_signtype', '1'),
        ('p3_orderno', str(pay_id)),
        ('p4_version', 'v2.8'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("jinyangpay query  data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_QUERY_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("jinyangpay query  rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)['data']
        trade_status = str(data['r5_orderstate'])
        trade_no = data['r2_systemorderno']
        total_fee = float(data['r4_amount'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 0.支付中1.成功, 2.失败，3.冻结
        if trade_status == '1':
            _LOGGER.info('jinyangpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('jinyangpay data error, status_code: %s', response.status_code)
